/*

This file is part of roomyak.

Copyright (C) 2008 Pixecur Technologies Incorporated (Esotera).
Visit Esotera at http://www.esoteras3.com
 
roomyak is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.
 
roomyak is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.
 
You should have received a copy of the GNU General Public License
along with roomyak; see the file COPYING.  If not, write to 
Pixecur Technologies, 213-31 Peet Street, St. John's, NL, A1B 3W8. 
 
Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
 
*/

package com.datasentinel.util.win32;

import java.awt.Image;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.imageio.ImageIO;

import com.datasentinel.util.thumbnail.ThumbnailException;
import com.sun.jna.WString;
import com.sun.jna.ptr.IntByReference;

public class Win32Helper
{
	
	private static Logger logger = Logger.getLogger(Win32Helper.class.getName());
	
	public static void openFileInDefaultEditor(final File file)
	{
		if(file == null || !file.exists())
			return;
		
		new Thread(){
			@Override
			public void run()
			{
				try
				{
					WString fileAbsolutePath =  new WString(file.getAbsolutePath());
					Win32UtilsLibrary.INSTANCE.OpenFileInDefaultEditor(fileAbsolutePath);
					Thread.sleep(10000);
				}
				catch(Exception e)
				{
					logger.log(Level.WARNING, "Error while opening file '" + file.getAbsolutePath() + "' in the default editor.", e);
				}
			}
		}.start();
	}

	
	public static void executeCommand(final String command, final File workingDirectory, final String arguments)
	{
		if(command == null || 
				(workingDirectory != null && !workingDirectory.exists()))
			return;
		
		new Thread(){
			@Override
			public void run()
			{
				try
				{
					WString shellCommand = new WString(command);
					WString shellWorkingDirectory= workingDirectory == null ? null : new WString(workingDirectory.getAbsolutePath());
					WString shellParameters = arguments == null ? null : new WString(arguments); 
					Win32UtilsLibrary.INSTANCE.ExecuteShellCommand(shellCommand, shellWorkingDirectory, shellParameters);
					Thread.sleep(10000);
				}
				catch(Exception e)
				{
					logger.log(Level.WARNING, "Error executing command: '" + command + "'.", e);
				}
			}
		}.start();
	}
	
	public static void executeCommand(final String command)
	{
		executeCommand(command, null, null);
	}
	
	/**
	 * @TODO Try to generate a thumbnail for the folder
	 */
	public static Image getThumbnail(byte[] pngBuffer, File file, boolean largeThumbnail) throws ThumbnailException
	{

		if(file == null || pngBuffer == null || !file.exists() || !file.isFile())
			return null;
		
		IntByReference bufferSizeRef = new IntByReference();
		bufferSizeRef.setValue(pngBuffer.length);
		WString fileAbsolutePath =  new WString(file.getAbsolutePath());
		boolean result = Win32UtilsLibrary.INSTANCE.ExtractFileThumbnail(fileAbsolutePath, largeThumbnail, bufferSizeRef, pngBuffer);
		
		int bufferSize = bufferSizeRef.getValue();
		logger.fine("Buffer size = " + bufferSize + ";result = " + result);
		
		if(result)
		{
			Image ans = null;
			try
			{
				ans = ImageIO.read(new ByteArrayInputStream(pngBuffer, 0, bufferSize));
			}
			catch (Exception e)
			{
				logger.log(Level.WARNING, "Error while reading the PNG data of the thumbnail for the file: [" + file.getAbsolutePath() + "]", e);
				throw new ThumbnailException(e);
			}
			return ans;
		}

		logger.warning("Error while generating thumbnail for the file: [" + file.getAbsolutePath() + "]");
		
		return null;
	}
	
	public static boolean setProcessPriorityBelowNormal()
	{
		return Win32UtilsLibrary.INSTANCE.SetProcessPriorityBelowNormal();
	}

	public static boolean setProcessPriorityNormal()
	{
		return Win32UtilsLibrary.INSTANCE.SetProcessPriorityNormal();
	}

	public static long getCurrentProcessId()
	{
		return Win32UtilsLibrary.INSTANCE.GetCurrentProcessNumericId();
	}

	public static int mapNetworkDrive(String remPath, String localPath, String userName, String password, boolean interactive, boolean prompt)
	{
		return Win32UtilsLibrary.INSTANCE.MapNetworkDrive(new WString(remPath), new WString(localPath), userName == null ? null : new WString(userName), password == null ? null : new WString(password), interactive, prompt);
	}

	public static String getNetworkDriveRemotePath(String localPath)
	{
		IntByReference bufferSizeRef = new IntByReference();
		bufferSizeRef.setValue(512);
		byte[] buffer = new byte[bufferSizeRef.getValue()];
		int result = Win32UtilsLibrary.INSTANCE.GetNetworkDriveRemotePath(new WString(localPath), buffer, bufferSizeRef);
		return result == 0 && bufferSizeRef.getValue() > 0 ? new String(buffer, 0, bufferSizeRef.getValue()) : "";
	}
	
	public static int deleteNetworkDrive(String devName, boolean updProfile, boolean force)
	{
		return Win32UtilsLibrary.INSTANCE.DeleteNetworkDrive(new WString(devName), updProfile, force);
	}
	
	boolean setWorkingSetSize(long minBytes, long maxBytes)
	{
		return Win32UtilsLibrary.INSTANCE.SetWorkingSetSize(minBytes, maxBytes);
	}

	
	
}
